<?php

class JdRank{

	/**
	 * 添加
	 *
	 */
	function add($data){
		
		$m = M('JdRank');
		//返回自增id
		$id = $m->add($data);
		
		return $id;
	}

	/**
	 * 修改
	 *
	 */
	function update_by_id($id,$upItems){
		$m = M('JdRank');
		return $m -> where('id='.$id)->save($upItems);
	}
	
	function get_by_id($id){
		$m = M('JdRank');
		return $m -> getById($id);
	}

    function get_by_ids($ids){
        $m = M('JdRank');
        $ranks = $m -> where("id IN ($ids)")->select();

        return map_array($ranks,'id');
    }

    function delete_by_id($id){
        $m = M('JdRank');
        return $m ->where('id='.$id)-> delete();
    }

	function get_by_admin_id($admin_id = null){

        $whereSql = '1 = 1';
        if(!is_null($admin_id)){
            $whereSql = 'j.admin_id='.$admin_id;
        }

		$m = M('JdRank');
		return $m->table('jd_rank j')
        ->where($whereSql)
        ->join('admin a ON a.id = j.admin_id')
        ->field("j.*,FROM_UNIXTIME(j.dateline) AS dateline_fmt,a.real_name")
        ->order('j.created DESC')
		->select();
	}

   function items_rank_js($ids){

       //1.日期范围
       $date_range = array();

       $date_str = '';
       for($i = 30;$i >= 0;$i--){

           if($i > 0){
               //日期
               $date            = date('Y-m-d', strtotime("-$i days"));
               $date_range[]    = $date;
           }else{
               //日期
               $date            = date('Y-m-d');
               $date_range[]    = $date;
           }

           //日期字符
           $date_str .= '<category label="'.$date.'" />\\'.PHP_EOL;
       }

       $date_range[]    = date('Y-m-d');

       //去最后的换行
       $date_str = rtrim($date_str,PHP_EOL);


       //2.排名详情
       $ranks_info = $this->get_by_ids($ids);


       //3.获取商品的排名
       import('@.ORG.JdRankLog');
       $this->JdRankLog = new JdRankLog();

       //获取记录
       $rank_logs = $this->JdRankLog->get_by_ids($ids);

       //分组数据
       $group_logs = $this->JdRankLog->group_logs($rank_logs);


       foreach($group_logs as $i => $l){
           $group_logs[$i] = array(
               'rank' => $ranks_info[$i],
               'logs' => $l
           );
       }

       //数据集
       $dataset = $this->item_dataset($group_logs,$date_range);

       //最终的js
       $js = <<<EOD
var dataString ='<chart baseFontSize="14" numberPrefix="第 " numberSuffix=" 位" caption="排名分析" subcaption="" xAxisName="日" yAxisName="排名"  legendPosition="BOTTOM" divLineIsDashed="1" palette1="3" pixelsPerPoint="15" axis="log" logBase="5" numMinorLogDivLines="3" paletteThemeColor1="FF0000" anchorMinRenderDistance="20" showToolTip="1" connectNullData="1" rotateValues="1" palette="4" labelHeight="100">\
<categories>\
	$date_str
</categories>\
$dataset
<trendlines>\
</trendlines>\
<styles>\
    <definition>\
    <style name="Font_0" type="font" font="Tahoma" size="16" underline="1"  color="930000"  />\
    <style name="Font_1" type="font" font="Times" size="22" color="4F4F4F" bold="0" align="right" Italic="1" bgcolor="DFDFDF" bordercolor="D0D0D0" />\
    </definition>\
    <application>\
    </application>\
    </styles>\
</chart>';
EOD;

       return $js;
   }


    /**
     * 排名数据集
     * @param $group_logs
     * @param $date_range
     * @return string
     */
    function item_dataset($group_logs,$date_range){

        $setStr = '';
        foreach($group_logs as $i=>$l){
            $id = $i;

            //日期排名
            $date_ranks = $l['logs'];

            $setValue = '';
            foreach($date_range as $d){
                $rank = 0;
                if(array_key_exists($d,$date_ranks)){
                    $rank = $date_ranks[$d];
                }
                $setValue .= '<set value="'.$rank.'" />\\'.PHP_EOL;
            }

            //去最后换行
            $setValue = rtrim($setValue,PHP_EOL);

            //换行
            $end_of_line = PHP_EOL;

            //排名详情
            $rank = $l['rank'];

            //颜色
            $color = $this->line_color($i);

            $setStr .= <<<EOD
            <dataset seriesName="{$rank['goods_name']}({$rank['item_id']})({$rank['shop_name']})" color="{$color}" lineThickness="1" >\
            $setValue
            </dataset>\\$end_of_line
EOD;
        }
        //去最后换行
        $setStr = rtrim($setStr,PHP_EOL);

        return $setStr;
    }

    /**
     * 获取商品信息
     * @param $item_id
     */
    function get_item_info_from_web($item_id){

        import('@.ORG.Snoopy');
        $snoopy = new Snoopy();

        $url = 'http://item.jd.com/'.$item_id.'.html';
        $snoopy->fetch($url);

        //去换行
        $html = remove_eol($snoopy->results);

        //匹配商品名称
        $matches_goods = array();
        preg_match('/<h1>(.*?)<\/h1>/',$html,$matches_goods);

        $goods_name = '';
        if(isset($matches_goods[1])){
            $goods_name = $matches_goods[1];
        }

        //匹配店铺名称
        $matches_shop_name = array();
        preg_match('/<a href=\"http:\/\/mall\.jd\.com\/index-(\d+)\.html\" target=\"_blank\">(.*?)<\/a>/',$html,$matches_shop_name);

        $shop_name = '';
        if(isset($matches_shop_name[2])){
            $shop_name = $matches_shop_name[2];
        }


        //获取要查询的链接
        $url = $this->get_url_from_html($html);

        return array(
            'goods_name' => gbk_to_utf8($goods_name),
            'shop_name'  => gbk_to_utf8($shop_name),
            'url'        => $url
        );
    }

    /**
     * 从页面获取的链接
     * @param $html
     * @return string
     */
    function get_url_from_html($html){

        //加s，点号可匹配换行符

        //找到面包屑
        preg_match('/<div class=\"breadcrumb\">(.*?)<\/div>/s',$html,$bread_match);

        $links_content  = '';
        $link_url       = '';

        if(!empty($bread_match)){
            $links_content = $bread_match[1];
        }else{
            return $link_url;
        }


        //匹配链接
        preg_match_all('/href="(.*?)"/',$links_content,$links_match);

        if(!empty($links_match)){
            $link_count = count($links_match[1]);
            //只取第三个位置的
            $pos = 3;
            if($link_count >= $pos){
                $link_url = $links_match[1][$pos-1];
            }
        }

        return $link_url;
    }

    function get_item_rank($item_id,$url,$page = 3){

        import('@.ORG.Snoopy');

        include_once(APP_PATH.'/Cls/lib_jd.php');

        $ranks = array(
            'item_id'   => $item_id,
            'url'       => $url,
            'page'      => $page
        );

        $top        = get_item_top($ranks);

        return $top;
    }

    function line_color($id){
        $color = '';
        switch($id % 5){
            case 0:
                $color = 'FF0000';
                break;
            case 1:
                $color = 'FFFF0';
                break;
            case 2:
                $color = '0000FF';
                break;
            case 3:
                $color = '00FF00';
                break;
            case 4:
                $color = 'FF00FF';
                break;
            default :
                $color = '000000';
                break;
        }
        return $color;
    }
}